package com.haiyou.dc.canal.canal.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.otter.canal.protocol.CanalEntry;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class RowChangeRabbitHandler implements RowChangeHandler {

    public static String tables = "qa_sys._user";

    public RowChangeRabbitHandler() {
        log.info("new RowChangeRabbitHandler()");
    }

    @Override
    public boolean handler(CanalEntry.Entry entry, CanalEntry.RowChange rowChange) {
        String tableName = entry.getHeader().getTableName().toLowerCase();
        if (!tables.contains(tableName)) {
            log.info("不处理table=" + tableName);
            return true;
        }
        List<CanalEntry.RowData> rows = rowChange.getRowDatasList();
        for (CanalEntry.RowData rowData : rows) {
            send(entry, rowChange, rowData);
        }
        return true;
    }

    private void send(CanalEntry.Entry entry, CanalEntry.RowChange rowChange, CanalEntry.RowData rowData) {
        CanalEntry.EventType eventType = rowChange.getEventType();
        String tableName = entry.getHeader().getTableName().toLowerCase();
        Long timestamp = entry.getHeader().getExecuteTime();
        List<CanalEntry.Column> beforeColumns = rowData.getBeforeColumnsList();
        List<CanalEntry.Column> afterColumns = rowData.getAfterColumnsList();
        JSONObject before = new JSONObject();
        //操作前
        for (CanalEntry.Column column : beforeColumns) {
            before.put(column.getName(), column.getValue());
        }
        //操作后
        JSONObject after = new JSONObject();
        for (CanalEntry.Column column : afterColumns) {
            after.put(column.getName(), column.getValue());
        }
        log.info("tableName==>" + tableName + ",timestamp==>" + timestamp);
        log.info("before==>" + before);
        log.info("after==>" + after);
        if (CanalEntry.EventType.INSERT == eventType) {
            //插入操作after
        } else if (CanalEntry.EventType.UPDATE == eventType) {
            //更新操作after
        } else if (CanalEntry.EventType.DELETE == eventType) {
            //删除操作before
        }
    }
}
